<template>
  <view class="main">

    <view class="input" :style="disabled?'background-color:#f5f7fa':''" v-if="showInput">
      <view @click="showModal" class="content"
            :style="{'color':disabled || (!_showValue && placeholder)? '#c0c4cc': ''}">{{ _showValue || placeholder }}
      </view>
      <text v-if="clearable&&!disabled" @click="empty" class="selectIcon iconcross"></text>
    </view>
    <view class="select-modal" :class="isShowModal?'show':''" @tap="hideModal">
      <view class="select-dialog" @tap.stop="" :style="{backgroundColor:bgColor}">
        <view class="select-bar bg-white">
          <view class="title">请选择</view>
          <text class="selectIcon iconcross" @click="hideModal"></text>
        </view>
        <view v-if="_value.length > 0" class="select-val bg-white">
          <view style="width: calc(100% - 80rpx); display: flex;overflow-x: scroll;">
            <view @tap="selectSwitch(index, item)" class="item"
                  :class="`${index === selectIndex ? 'select':''}`" v-for="(item,index) in _value"
                  :style="`${index === selectIndex ? 'border-color: ' + selectColor : ''}`"
                  :key="index">
              <view :style="index === selectIndex?'color:'+selectColor+';':''">{{ item.label }}</view>
            </view>
          </view>

          <view style="width: 80rpx;">
            <u-button type="primary" size="mini" @click="hideModal">确定</u-button>
          </view>
        </view>

        <view class="select-content">
          <view class="select-item" v-for="(item,index) in _list" :key="index"
                :style="valueIndexOf(item)?'color:'+selectColor+';background-color:'+selectBgColor+';':'color:'+color+';'"
                @click="select(item)">
            <view class="title">{{ getLabelKeyValue(item) }}</view>
            <text class="selectIcon icongou" v-if="valueIndexOf(item)"></text>
          </view>

        </view>

      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isShowModal: false,
      isLast: false,
      selectIndex: 0,
      isSwitch: false,
      isEcho: true,
      fullPath: undefined,
      fullPathParent: {},
      tabChildren: undefined,
      firstParent: undefined,
      chooseAttr: []
    }
  },
  props: {
    value: {
      default: () => [],
      required: true,
      type: Array
    },
    placeholder: { // 占位符
      default: "",
      type: String
    },
    list: {
      default: () => [],
      required: true,
      type: Array
    },
    valueKey: { // 指定list中valueKey的值作为下拉框绑定内容
      default: 'value',
      type: String
    },
    labelKey: { // 指定list中labelKey的值作为下拉框显示内容
      default: 'label',
      type: String
    },
    disabled: {
      default: false,
      type: Boolean
    },
    clearable: {
      default: false,
      type: Boolean
    },
    color: {
      default: "#000000",
      type: String
    },
    selectColor: {
      default: "#0081ff",
      type: String
    },
    bgColor: {
      default: "#F1F1F1",
      type: String
    },
    selectBgColor: {
      default: "#FFFFFF",
      type: String
    },
    /**
     * 是否展示输入框
     */
    showInput: {
      default: true,
      type: Boolean
    }
  },
  watch: {
    selectIndex(newVal) {
      this.isSwitch = !this.isSwitch
    },
    value(newVal) {
      if (this.isEcho) {
        this.echo()
      }
    },
    list(newVal) {
      if (!newVal) return
      if (newVal.length < 1) return
      this.initFullPath(newVal)
    }
  },
  computed: {
    _value: {
      get() {
        return this.get_value()
      },
      set(val) {

      }
    },
    _showValue: {
      get() {
        return this.get_showValue()
      },
      set(val) {

      }
    },
    _list: {
      get() {
        let list = this.list
        if (list.length < 1) return
        if (this.tabChildren) {
          return this.tabChildren
        } else {
          for (let i = 0; i < this.value.length; i++) {

            let item = this.value[i]
            let choose = list.find(temp => {
              return this.getValueKeyValue(temp) === item
            })
            if (choose.children && choose.children.length > 0) {
              list = choose.children
            }
          }
          return list
        }
      },
      set(val) {

      }
    }
  },
  onLoad() {
    if (!this.fullPath) {
      this.initFullPath(this.list)
    }
  },
  created() {
    if (!this.fullPath) {
      this.initFullPath(this.list)
    }
  },
  onReady() {
    if (!this.fullPath) {
      this.initFullPath(this.list)
    }
  },
  methods: {
    open(value) {
      if (value && value.length > 0) {
        this.$emit('update:value', value)
        this.$emit('change', value)
      }
      this.isShowModal = true
    },
    echo() { // 回显
      this.isEcho = false
      // let val = this.value
      // let chooseAttr = []
      // let list = this.list
      // val.forEach(item => {
      //   let choose = list.find(temp => {
      //     return this.getValueKeyValue(temp) === item
      //   })
      //   chooseAttr.push(choose)
      //   if (choose.children && choose.children.length > 0) {
      //     list = choose.children
      //   }
      // })
      // let index = chooseAttr.length - 1
      // this.selectIndex = this.value.length -1
      // this.isLast = true
      // if (chooseAttr.length < 1) return
      // if (chooseAttr[index].children && chooseAttr[index].children.length > 0) {
      //   this.isLast = false
      // } else {
      //   this.isLast = true
      // }
      console.log('回显 -> ', this.value)
      this.selectIndex = this.value.length - 1
    },
    get_value() {
      let val = this.value
      let chooseAttr = []
      let list = this.list
      val.forEach(item => {
        let choose = list.find(temp => {
          return this.getValueKeyValue(temp) === item
        })
        chooseAttr.push(choose)
        if (choose.children && choose.children.length > 0) {
          list = choose.children
        }
      })
      return chooseAttr
    },
    get_showValue() { // 将数组值转换为以 / 隔开的字符串
      return this.get_value().map(temp => this.getLabelKeyValue(temp)).join(' / ')
    },
    select(item) { // 点击选项

      // console.log(item)
      let path = this.findParent(item.value)
      // console.log('path -> ', path)
      this.setInput(path)
      // this.setTabHead(path)

      this.isEcho = false
      let val = this.getValueKeyValue(item)
      let choose = this._list.filter(t => t.value === val)[0]
      let _val = this.value

      // console.log('path -> ', _val)

      this.selectIndex = path.length - 1


      if (choose.children && choose.children.length > 0) {
        this.isLast = false
        this.isSwitch = true
        this.tabChildren = choose.children
      } else {
        this.isLast = true
        this.isSwitch = false
      }

    },
    valueIndexOf(item) {
      let val = this.getValueKeyValue(item)
      return this.value.filter(t => t === val).length > 0
    },
    getLabelKeyValue(item) { // 获取label
      return item[this.labelKey]
    },
    getValueKeyValue(item) { // 获取value
      return item[this.valueKey]
    },
    selectSwitch(index, item) {
      // let val = this.value[index]
      // this.selectIndex = index
      if (!this.fullPath) {
        this.initFullPath(this.list)
      }
      this.selectIndex = index
      this.tabChildren = this.fullPathParent[item.parentId]

      // this._list = this.fullPathParent[item.parentId]
      // console.log(item, this.fullPathParent[item.parentId])
    },
    empty() { // 清空
      if (!this.fullPath) {
        this.initFullPath(this.list)
      }
      this.setInput([])
      this.tabChildren = this.fullPathParent[this.list[0].parentId]
    },
    setInput(val) {
      this.$emit('update:value', val)
      this.$emit('change', val)
    },
    showModal() { // 显示model
      if (!this.disabled) {
        this.isShowModal = true
        // this.$emit('input', [])
        this.$emit('visible-change', true)
      }
    },
    hideModal() { // 隐藏model
      this.isShowModal = false
      this.$emit('visible-change', false)
    },
    initFullPath(list) {
      let that = this
      that.fullPath = {}

      list.forEach(item => {
        that.fullPath[item.value] = {
          parentId: item.parentId,
          path: item.value + '',
          // item: { label: item.label, value: item.value }
          item: item
        }
        if (item.children && item.children.length > 0) {
          that.initFullPathChildren(item.children, item, that)
        }
      })
      // console.log('初始化完成 -> ', that.fullPath)
      this.fullSet(that.fullPath, that)
      // this.setTabHead(this.value)
      return that.fullPath
    },
    initFullPathChildren(list, parent, that) {
      if (!list) return
      if (list.length < 1) return
      list.forEach(item => {
        that.fullPath[item.value] = {
          parentId: item.parentId,
          path: that.fullPath[parent.value].path + ',' + item.value,
          // item: { label: item.label, value: item.value },
          item: item
        }

        if (item.children && item.children.length > 0) {
          that.initFullPathChildren(item.children, item, that)
        }
      })


    },
    fullSet(list, that) {
      let lset = new Map()
      for (const key in list) {
        if (lset[list[key].parentId]) {
          lset[list[key].parentId].push(list[key].item)
        } else {
          lset[list[key].parentId] = [list[key].item]
        }
      }

      that.fullPathParent = lset
    },
    // 查找父级
    findParent(val) {
      if (!this.fullPath) {
        this.initFullPath(this.list)
      }
      let arr = []
      this.fullPath[val].path.split(',').forEach(value => arr.push(Number(value)))
      return arr
    },
    setTabHead(val) {
      let aa = null
      if (val) {
        aa = val
      } else {
        aa = this.value
      }
      let arr = []
      aa.forEach(item => {
        arr.push(this.fullPath[item].item)
      })
      this.chooseAttr = arr
      console.log(this.chooseAttr)
    }
  }
}
</script>
<style>
@font-face {
  font-family: "selectIcon";
  src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208'); /* IE9 */
  src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAMEAAsAAAAABvQAAAK4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDBgqBRIFCATYCJAMMCwgABCAFhQUHNRsfBsg+QCa3uoO0oAJTMwhxVu965keqWBy1hkbwtfzWb2Z279/shRhJisKF6FApKLI7oyBbpAaHo3w24k+ca9EUJbDmjaeznUdZ/FOUlkWdJ33rizZY/Pw6J5Xw0qKYxHTMesePHVT6EFpaC4zV70sKi2bYgNPc1w0WHnDVC/e/UnNTgyP+4Jq6BBpIHoisgypLaIAFEtU0wgeaIG8Yu4nAIZwnUK1QgFfOT6nUUoBpgXjj2lqplTMpiuXtCW3N2iK+aPTS2/Qdnzny8d+5IEiaDMy99exklra//FrKnX48pChmgrq5QcYRQCEe17ruqgqLAKv8WntwqwhpLms/nB5yW/iHRxJEC0QOgT3NnfgF01NBKvOuIzNoZdh5gJuAeGrsozE8vOJ7u5D832oz55039W5G+S52K0H+zNf1TJz07k26kqoQybRfwVFV4rjDS/K8EXUyuF1cXnT3weKS9Rvdm/xe7h8oA1hLwOR18R+Y4n4zwpr4z5SU089Vc+cpfWL+mn5APmT3Z39jeOs/GbWjK+DnmsuL/u6ehMX4j4yedSVkAUUuPh3TY022MtKZUEOtPqCb8Bkvnr5XT6imU0gGrEJW7aAL/gw0OhegVV2F6pC7uTOppirKIA4MFQhTrpCM+AbZlDu64L/QmAkQWlMhQXU75D07O9Gtl0PUYjTBLyAzOLNQYtypIEEjvsXtBLQTooV2nrQrGEau2gKmZlR4L8gwnGtBJbUn1diCOOQUnEkTkRAOeci9KHOQxvFro+tx3ZcGAaeljstCSBNDJuArgIyBYyy6OdZxAhHIELu1IC9AtgShCVtLltEKrSff1XoHJo3RC33hM63o3j6pSNkmqmIWEAtxFHB2OwoRBAfyeqE3r2ogHeF42dBhs7gvf7CukH5MmlUGOCpHihxFfs6TehDyKCqVAA==') format('woff2'),
  url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.woff?t=1590375117208') format('woff'),
  url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.ttf?t=1590375117208') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.svg?t=1590375117208#selectIcon') format('svg'); /* iOS 4.1- */
}

.selectIcon {
  position: absolute;
  right: 16rpx;
  font-family: "selectIcon" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icongou:before {
  content: "\e61c";
}

.iconcross:before {
  content: "\e61a";
}

</style>
<style lang="scss" scoped>
.main {
  font-size: 28rpx;
}

.bg-white {
  background-color: #FFFFFF;
}

.input {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  height: 60rpx;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  border-style: solid;
  border-width: 1rpx;
  border-color: rgba(0, 0, 0, 0.1);

  .content {
    display: flex;
    align-items: center;
    height: 100%;
    width: 100%;
  }
}

.select-modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: -8rpx;
  left: 0;
  z-index: 9999;
  opacity: 0;
  outline: 0;
  text-align: center;
  -ms-transform: scale(1.185);
  transform: scale(1.185);
  backface-visibility: hidden;
  perspective: 2000rpx;
  background: rgba(0, 0, 0, 0.6);
  transition: all 0.3s ease-in-out 0s;
  pointer-events: none;
  margin-bottom: -1000rpx;

  &::before {
    content: "\200B";
    display: inline-block;
    height: 100%;
    vertical-align: bottom;
  }

  .select-dialog {
    position: relative;
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    background-color: #f8f8f8;
    overflow: hidden;
    width: 100%;
    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;

    .select-content {
      text-align: left;
      padding: 20rpx;
      background-color: #FFFFFF;
      min-height: 520rpx;
      max-height: 520rpx;
      overflow: auto;

      .select-item {
        position: relative;
        padding: 20rpx;
        display: flex;

        .title {
          flex: 1;
        }
      }
    }
  }
}

.select-modal.show {
  opacity: 1;
  transition-duration: 0.3s;
  -ms-transform: scale(1);
  transform: scale(1);
  overflow-x: hidden;
  overflow-y: auto;
  pointer-events: auto;
  margin-bottom: 0;
}

.select-bar {
  padding: 0 20rpx;
  display: flex;
  position: relative;
  align-items: center;
  min-height: 100rpx;
  justify-content: center;

  .title {
    font-size: 28rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    height: 100%;
    justify-content: center;
    max-width: 100%;
  }
}

.select-val {
  display: flex;
  width: 750rpx;
  white-space: nowrap;
  overflow-x: scroll;
  width: 100%;
  padding: 20rpx 20rpx 0 20rpx;
  border-bottom-style: solid;
  border-bottom-width: 1rpx;
  border-color: #e8eaed;

  .item {
    padding-left: 10rpx;
    padding-right: 10rpx;
    padding-bottom: 10rpx;
  }

  .select {
    border-bottom-style: solid;
    border-bottom-width: 3rpx;
  }
}
</style>
